ordered_chats = [];
var objectId = "000000";
var chat_logs = {};

function documentReady() {
    console.log('in documentReady');
    getContacts();
    $(".contacts_list").hide;
    getChats();

    $(".tab_item").on("click", function(){
        if(this.title=="通讯录") {
            hideElement();
            getContacts();
            $(".nav_view").append("<div id='letter'></div>");
            contacter();
        } else if(this.title=="聊天") {
            $("#letter").remove();
            $(".Initials ul li").remove();
            getChats();
        }
    });


    document.oncontextmenu = function() {
        return false;
    };
}

function contacter(){
    console.log('in contacter');
    var Initials = $('.Initials');
    console.log(Initials);
    var LetterBox=$('#letter');
    Initials.find('ul').append('<li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li><li>H</li><li>I</li><li>J</li><li>K</li><li>L</li><li>M</li><li>N</li><li>O</li><li>P</li><li>Q</li><li>R</li><li>S</li><li>T</li><li>U</li><li>V</li><li>W</li><li>X</li><li>Y</li><li>Z</li><li>#</li>');
    initials();
       $(".Initials ul li").click(function(){
                var _this=$(this);
                var LetterHtml=_this.html();
                LetterBox.html(LetterHtml).fadeIn();

                //Initials.css('background','rgba(145,145,145,0.6)');
                
                setTimeout(function(){
                    Initials.css('background','rgba(145,145,145,0)');
                    LetterBox.fadeOut();
                },1000);

                var _index = _this.index();
                if(_index==0){
                    $('#J_NavChatScrollBody').animate({scrollTop: '0px'}, 300);//点击第一个滚到顶部
                }else if(_index==27){
                    var DefaultTop=$('#default').position().top;
                    $('#J_NavChatScrollBody').animate({scrollTop: DefaultTop+'px'}, 300);//点击最后一个滚到#号
                }else{
                    var letter = _this.text();
                    if($('#'+letter).length>0){
                        var LetterTop = $('#'+letter).position().top;
                        $('#J_NavChatScrollBody').animate({scrollTop: LetterTop-45+'px'}, 300);
                    }
                }
    });
}

/*
$(document).ready(function(){
    $(".tab_item").on("click", function(){
        if(this.title=="通讯录") {
			hideElement();
			getContacts();
            $(".nav_view").append("<div id='letter'></div>");
            contacter();
		} else if(this.title=="聊天") {
            $("#letter").remove();
            $(".Initials ul li").remove();
			getChats();
		}
    });
	
	
	document.oncontextmenu = function() {
		return false;
	}
	
});*/

function hideElement() {
    console.log('in hideElement');
	$("#sdialog-rclick-menu-div").hide()
	$("#mdialog-rclick-menu-div").hide()
}

//置顶聊天
function stickDialog(title) {
    console.log('in stickDialog');
	ordered_chats.splice(ordered_chats.indexOf(title), 1);
	ordered_chats.unshift(title);
	getChats();
	hideElement();
}

function showNoChat() {
    console.log('in showNoChat');
	$e = $("#J_NavChatScrollBody");
	$div = $("<div class='empty_chat_list'></div>");
	$span = $("<span class='empty_chat_list'>暂无新消息</span>");
	$div.append($span);
	$e.empty();
	$e.append($div);	
}

function addMouseDownListener() {
    console.log('in addMouseDownListener');
	//$("#J_NavChatScrollBody").children("div").mousedown(function(e) {
	$(".chat_item").mousedown(function(e) {
		hideElement()
		//点击鼠标右键
		if(e.which == 3) {
			var obj = e.target
			var dtype = e.target.getAttribute("dialogType") || "single";
			var title = obj.getAttribute("title");
			
			var $ele = $("#sdialog-rclick-menu-div")
				
			if(dtype == 'multi') {
				$ele = $("#mdialog-rclick-menu-div")
				var nickname = chats[title].nickname;
			}
	
			var X = e.pageX;
			var Y = e.pageY;
			
			var clickListener = function(e) {
				var funcId = e.target.getAttribute("func");
				
				switch(funcId) {
					case '1': 
						stickDialog(title);
						break;
					case '2': 
						ordered_chats.splice(ordered_chats.indexOf(title), 1);
						//ordered_chats.length = 0;
						getChats();
						
						if(!ordered_chats.length) {
							showNoChat();
						}
						break;
					default: 
						//解除监听，防止多次绑定					
						$("button.btnClose").off('click').click(function(e) {
							$("#modifyNameBg").hide();
						});
						
						$("button.btnConfirm").off('click').click(function(e) {
							var mName = $("#modifyGroupNameDiv input").val();
							var gid = contacts[obj.getAttribute('title')].ID;

							$.ajax({
								url: ip + "modifyGroupName",
								type: 'get',
								dataType: 'json',
								contentType: 'application/json; charset=utf-8',
								data: {
                                    'groupid': gid,
                                    'groupname': mName,
                                    'uid': userId
                                },

								success: function(data) {
								    console.log(data);
                                    // data = JSON.parse(data);
                                    if(data['success'] == "yes") {
                                        $(obj).find("span.nickname_text").text(mName);
                                        chats[title].nickname = mName;
                                    } else {
                                        console.log("修改群名失败");
                                    }
								},

								error: function() {

								}
							});

							$("#modifyNameBg").hide();
						});
						
						$("#modifyNameBg").show();
						$("#modifyGroupNameDiv input").val(nickname);
						hideElement();
						
				}
			}
			
			$("#sdialog-rclick-menu-div").unbind('click').click(clickListener);//添加监听器前先移除之前的监听
			$("#mdialog-rclick-menu-div").unbind('click').click(clickListener);
			
			$ele.show().css({
				left: X,
				top: Y
			});
		}
	});
	
}


var chat_records = {
	"梓桐": {
		"2017-10-11": [{"nickname":"阿门", "time":"15:02:02", "msg":"我今天见到梓桐了。"}, {"nickname":"贝塔", "time":"20:33:44", "msg":"我今天约了梓桐一起去逛街。"}],
		"2017-11-15": [{"nickname":"西格玛", "time":"01:12:32", "msg":"梓桐最近挺忙的。"}]
	},
	"导员": {
		"2017-10-11": [{"nickname":"阿门", "time":"15:02:02", "msg":"我今天见到导员了。"}, {"nickname":"贝塔", "time":"20:33:44", "msg":"我今天约了导员一起去逛街。"}],
		"2017-11-15": [{"nickname":"西格玛", "time":"01:12:32", "msg":"导员最近挺忙的。"}]
	},
	"灿美": {
		"2017-10-11": [{"nickname":"阿门", "time":"15:02:02", "msg":"我今天见到灿美了。"}, {"nickname":"贝塔", "time":"20:33:44", "msg":"我今天约了灿美一起去逛街。"}],
		"2017-11-15": [{"nickname":"西格玛", "time":"01:12:32", "msg":"灿美最近挺忙的。"}],
		"2017-11-28": [{"nickname":"阿门", "time":"15:02:02", "msg":"灿美今天要考试。"}, {"nickname":"贝塔", "time":"20:33:44", "msg":"我今天约了灿美一起去逛街。"}],
		"2017-12-05": [{"nickname":"西格玛", "time":"01:12:32", "msg":"灿美最近挺忙的。"}],
		"2017-01-01": [{"nickname":"西格玛", "time":"00:00:01", "msg":"灿美，新年快乐！"}],		
		"2017-01-04": [{"nickname":"阿门", "time":"15:02:02", "msg":"灿美今天要考试。"}, {"nickname":"贝塔", "time":"20:33:44", "msg":"我今天约了灿美一起去逛街。"}],
		"2017-01-06": [{"nickname":"西格玛", "time":"01:12:32", "msg":"今天灿美好像还有最后一场考试。"}],
	},	
	
};


function searchMessage() {
    console.log('in searchMessage');
	$("#recordBg").show();
	
	$("button.btnClose").click(function() {
		$("#recordBg").hide();
		$("#messageDiv").empty();
		$("#searchVal").val("");
	});
}

function showSearch() {
    console.log('in showSearch');
	$("#messageDiv").empty();
	var kw = $("#searchVal").val();
	for(var date in chat_records[kw]) {
		var $sep = $(document.createElement("div"));
		$sep.addClass("seperator");
		var $date = $(document.createElement("span"));
		$date.text(date);
		$sep.append($date);
		$("#messageDiv").append($sep);
		
		alist = chat_records[kw][date];
//		alert(chat_records[kw][date]);
		
		for(var data in alist) {
			data = alist[data]
			var $remsg = $(document.createElement("div"));
			$remsg.addClass("remsg");
			
			var $msgTitle = $(document.createElement("div"));
			$msgTitle.addClass("msgTitle");
			
			var $msgCtxt = $(document.createElement("div"));
			$msgCtxt.addClass("msgCtxt");
			$msgCtxt.text(data['msg']);
			
			var $msgName = $(document.createElement("span"));
			$msgName.addClass("msgName");
			$msgName.text(data['nickname']);
			var $msgTime = $(document.createElement("span"));
			$msgTime.addClass("msgTime");
			$msgTime.text(data['time']);
			
			$msgTitle.append($msgName)
			$msgTitle.append($msgTime);
			$remsg.append($msgTitle, $msgCtxt);
			$("#messageDiv").append($remsg);
		}
	}
//	$("#messageDiv").show();
}

//获取聊天列表------------------------------------------------
function getChats() {
    console.log('in getChats');
    $(".chat").css("background-color","");
    $(".chat[title='聊天']").css("background-color","#26292e");
    $("#J_NavChatScrollBody").empty();
    for(var i in ordered_chats) {
		i = ordered_chats[i]
        $("#J_NavChatScrollBody").append(
		//生成聊天条目
         //   "<div class=\"chat_item slide-left ng-scope\" title='"+ i +"'><div class=\"ext\"><p class=\"attr\">19:32</p></div><div class=\"avatar\"><img src=" + chats[i].photo + " class=\"img\"></div><div class=\"info\"><h3 class=\"nickname\" style=\"display: block;margin:0px\"><span class=\"nickname_text\">" + chats[i].nickname + "</span></h3><p class=\"msg ng-scope\"><span>吾皇万岁万岁万万岁</span></p></div></div>"
        "<div class=\"chat_item slide-left ng-scope\" " + "dialogType='" + chats[i].dialogType + "' title='"+ i +"'>" +
            "<div class=\"ext overlay\"><p class=\"attr overlay\">19:32</p></div>" +
            "<div class=\"avatar overlay\"><img src=" + chats[i].photo + " class=\"img overlay\"></div><div class=\"info overlay\">" +
            "<h3 class=\"nickname overlay\" style=\"display: block;margin:0px\"><span class=\"nickname_text overlay\">" + chats[i].nickname + "</span></h3>" +
            "<p class=\"msg ng-scope overlay\"><span>吾皇万岁万岁万万岁</span></p></div></div>"
			
		);
    }

	if(!ordered_chats.length) {
		showNoChat();
	}	
	//给聊天条目添加左键单击功能
    $(".chat_item").on('click', function(e){
        $(".chat_item").css("background-color","");
        $(this).css("background-color","#26292e");
        $("#right_contacts").attr("style","display: none");
        $("#right_myself").attr("style","display: none");
        $("#right_default").show();
        $("#title_name").data("to",this.title);
        var avatar = $(this).children().eq(1).children().eq(0).attr("src")
        sessionStorage.setItem("chat_img",avatar);
        channel(this.title);
    });
	
	addMouseDownListener();
	hideElement();
}

//获取联系人列表---------------------------------------
function getContacts() {
    console.log('in getContacts');
    $(".chat").css("background-color","");
    $(".chat[title='通讯录']").css("background-color","#26292e");
    $("#J_NavChatScrollBody").empty();
    for(var i in contacts) {
        $("#J_NavChatScrollBody").append(
            //生成联系人条目
            "<div class=\"chat_item slide-left ng-scope contact-people\" title='"+ i +"'><div class=\"ext\"><p class=\"attr\">19:32</p></div><div class=\"avatar\">" +
            "<img src=" + contacts[i].photo + " class=\"img\"></div><div class=\"info\"><h3 class=\"nickname\" style=\"display: block;margin:0px\"><span class=\"nickname_text\">"
            + contacts[i].nickname + "</span></h3><p class=\"msg ng-scope\"><span>吾皇万岁万 岁万万岁</span></p></div></div>"
        );
    }
    //给联系人条目添加左键单击功能
    $(".chat_item").on('click', function(){
        $(".chat_item").css("background-color","");
        $(this).css("background-color","#26292e");
        $("#right_default").attr("style","display: none");
        $("#right_myself").attr("style","display: none");
        //对指定联系人赋予对应的信息
        $("#cont_photo").attr("src",contacts[this.title].photo);//头像
        $("#cont_Nick").text(contacts[this.title].nickname);
        // $("#cont_nickName").text(contacts[this.title].nickname);
        $("#cont_nickName_input").attr("value",contacts[this.title].nickname);
        $("#cont_userName").text(contacts[this.title].userName);
        $("#cont_department").text(contacts[this.title].department);
        $("#cont_ID").text(contacts[this.title].ID);
        $("#cont_ID").data("id",contacts[this.title].ID);
        $("#right_contacts").show();
        $("#title_name").data("to",this.title);
        var title = this.title;

        $(".button_send").click(function () {
            $("#right_contacts").attr("style","display: none");
            $("#right_myself").attr("style","display: none");
            $("#title_name").text($("#cont_Nick").text());
            $("#title_name").data("id",contacts[title].ID);
            $(".message .chat_avatar").attr("src",$("#cont_photo").attr("src"));//聊天对象的头像
            sessionStorage.setItem("chat_img",$("#cont_photo").attr("src"));
            $(".me .chat_avatar").attr("src",$("#headPic").attr("src"));//我的头像
            $("#message_list").children().remove();
            $("#right_default").show();
            //channel(title);
        });

        $(".button_del").unbind('click').click(function() {
            var uid = contacts[title].ID;
            $.ajax({
                url: ip + "sendDeleteFri",
                type: 'get',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: {
                    "fid": uid,
                    "uid": userId
                },

                success: function(data) {
                    console.log(data)
                },
                error: function() {

                }
            });
        });

        //修改好友备注
        $("#cont_nickName_input").blur(function () {
            contacts[title].nickname = $("#cont_nickName_input").val();
            $("#cont_Nick").text(contacts[title].nickname);
            $("#cont_nickName_input").attr("value",contacts[title].nickname);
            //需要刷新联系人列表
			
			getContacts();
        });
    });

}

//当前聊天信息框切换到id频道------------------------------------
function channel(id) {
    $(".group_member_panel").css("display", "none");
    $("#btnShowMember").attr("class", "directDown");

    $("#btnShowMember").attr("gid", id);

    console.log('in channel');
    objectId = id;
    var channel = chat_logs[id];
    var friend = contacts[id];

    $(".main-right .title_name").attr("title", id);
    var num= id.replace(/[^0-9]/ig,"");
    $("#title_name").data("id",num)
    objectId = id;
    $(".main-right .title_name").text(friend.nickname);
    $(".chat_area .box_bd").empty();
    //$(".message .chat_avatar").attr("src")
    for(var i in channel){
        var from_id = channel[i].from;
        //var from = contacts[from_id];
        if(from_id == userId) messageAddRight(from_id, channel[i].content, channel[i].msgStyle);
        else messageAddLeft(from_id, channel[i].content, channel[i].msgStyle);
    }
    stickToBottom();
}

//右边消息-----------------------------------------------------
function messageAddRight(fromId , content, msgStyle){
    console.log('in messageAddRight');
    if(msgStyle=="txt"){
    $(".chat_area .box_bd").append(
        //生成聊天信息内容
    "<div  class=\"message me\" ><img class=\"avatar\" src=\""+ $("#headPic").attr("src") +"\"  title='It's me!'><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default right\"  ><div class=\"bubble_cont\" ><div class=\"plain\">"+content+"</div> </div></div></div></div>"

    );}
    else if (msgStyle=="pic") {
        $(".chat_area .box_bd").append(
            //生成聊天信息内容
            "<div  class=\"message me\" ><img class=\"avatar\" src=\"" + $("#headPic").attr("src") + "\"  title='It's me!'><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default right\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><img class = \"message_picture\" src=\"" + content + "\"/></div> </div></div></div></div>"
        );
    }
}

function addChat(id, message) {
    console.log('in addChat');
    chat_logs.id += message;

}

//左边消息------------------------------------------------------
function messageAddLeft(fromId , content, msgStyle){
    //接收消息为{"from":3,"message":"潇洒下","to":5,"type":"msg"}
        if (msgStyle == "txt") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src='"+sessionStorage.getItem("chat_img")+"'><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\">" + content + "</div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "pic") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src='"+sessionStorage.getItem("chat_img")+"'><div class=\"content\"> <div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><img class = \"message_picture\" src=\"" + content + "\"/></div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "file") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src=\"./images/4.jpg\" ><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><a  href=\"" + content + "\"><img class='message_file' src='images/00.jpg'></img></a></div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "audio") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src=\"./images/4.jpg\" ><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><audio  src='" + content + "'  controls='controls'>buhaoyisibuzhichi</audio></div> </div></div></div></div>"
            );
        }
    //}
    var div = document.getElementById("message_list");
    div.scrollTop = div.scrollHeight;
}
//左边消息------------------------------------------------------
function groupMessageAddLeft(fromId , content, msgStyle){
    //接收消息为{"from":3,"message":"潇洒下","to":5,"type":"msg"}
        if (msgStyle == "txt") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src='"+content.avatar+"'><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\">" + content.message + "</div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "pic") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src='"+content.avatar+"'><div class=\"content\"> <div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><img class = \"message_picture\" src=\"" + content.content + "\"/></div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "file") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src=\"./images/4.jpg\" ><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><a  href=\"" + content + "\"><img class='message_file' src='images/00.jpg'></img></a></div> </div></div></div></div>"
            );
        }
        else if (msgStyle == "audio") {
            $(".chat_area .box_bd").append(
                //生成聊天信息内容
                "<div  class=\"message you\" ><img class=\"avatar\" src=\"./images/4.jpg\" ><div class=\"content\"><div class=\"bubble js_message_bubble ng-scope bubble_default left\"  ><div class=\"bubble_cont\" ><div class=\"plain\"><audio  src='" + content + "'  controls='controls'>buhaoyisibuzhichi</audio></div> </div></div></div></div>"
            );
        }
    //}
    var div = document.getElementById("message_list");
    div.scrollTop = div.scrollHeight;
}
//发送消息-----------------------------------------------------
function sendMessage() {
    var sendMessageContent  = $("#inputArea").val();
    var from = userId;
    var to = $("#title_name").data("id");
    var flag = $("#title_name").data("to").replace(/[^a-z]+/ig,"");
    if (online === 1 && sendMessageContent!="") {//如果用户在线
        messageAddRight(from,sendMessageContent,"txt");
        if (flag === "u") {
            var msg=JSON.stringify({
                "from": from,
                "to": to,
                "message": sendMessageContent
            });
            websocket.send(msg)
        }
        if (flag === "g") {
            var msg=JSON.stringify({
                "gid": to,
                "uid": from,
                "message": sendMessageContent,
                "avatar": $("#headPic").attr("src")
            });
            websocket.send(msg)
        }

    }
    $("#inputArea").val("");
    var div = document.getElementById("message_list");
    div.scrollTop = div.scrollHeight;

}


//发送图片消息；
var upload_file_a = document.getElementById("upload_file_a");
var upload_file_input = document.getElementById("upload_file_input");

upload_file_a.addEventListener('click', function (e) {
    var evt = new MouseEvent("click", {bubbles: false, cancelable: true, view: window});
    upload_file_input.dispatchEvent(evt);


}, false);


//将选择的图片作为消息发出
function selectImageAsMessage(file) {
    console.log('in selectImageAsMessage');
    if(!file.files || !file.files[0]){
        return;
    }
    var imgURL = "";
    var reader = new FileReader();
    reader.onload = function(event){
        //document.getElementById('image').src = evt.target.result;
        imgURL = event.target.result;
        messageAddRight(userId, imgURL, "pic");
        stickToBottom();

    }
    reader.readAsDataURL(file.files[0]);
    var to = $("#title_name").data("id");
    var flag = $("#title_name").data("to").replace(/[^a-z]+/ig,"");
    if (flag === "u") {
        var action = "http://10.103.240.160:8080/sendPicToOne?from="+userId+"&to="+to+"&time=2017"
        $('#senfPic').attr("action",action)
        $('#senfPic').submit();
    }
    if (flag === "g") {
        var avatar = $("#headPic").attr("src");
        var action_group = "http://10.103.240.160:8080/sendPicToGroup?gid="+to+"&uid="+userId+"&time=2017&avatar="+avatar
        $('#senfPic').attr("action",action_group)
        $('#senfPic').submit();
    }

}

//聊天界面定位至最下面
function stickToBottom(){
    console.log('in stickToBottom');
    var div = document.getElementById("message_list");
    div.scrollTop = div.scrollHeight;
}

// 发起聊天功能中点击改变选中功能的样式
function change_select(self,another,divname,anotherDiv) {
    console.log('in change_select');
    var self = document.getElementById(self);
    var another = document.getElementById(another);
    var div = document.getElementById(divname);
    var anotherDiv = document.getElementById(anotherDiv);

    var self_class = self.className;
    var another_class = another.className;

    if (self_class == "nav_tab"&&another_class=="nav_tab selected") {
        self.setAttribute("class", "nav_tab selected");
        another.setAttribute("class", "nav_tab");
        div.setAttribute("style","display: block");
        anotherDiv.setAttribute("style","display: none");
    }
}

function onGenChat() {
    console.log('in onGenChat');
    var _cis = $("i[class*='web_chat_choose_green']");
    var ids = [];
    _cis.each(function () {
        ids.push($(this).attr('id'));
    });

    ids.push(userId);

    // console.log(ids);


    $.ajax({
		url: ip + 'createGroup',
		type: 'post',
		datatype: 'json',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify({
            "uid": userId,
            "members": ids
        }),

		success: function(data) {
			data = JSON.parse(data);
		},

		error: function() {

		}
	});

	
	$('#myModal_chat').modal('hide');
	
/* 	var chatsobj = {"nickname": "新聊天", "photo": "images/5.jpg", "dialogType": "multi"}
	var contactsobj = {"nickname":"新聊天","photo":"images/5.jpg","userName":"一个新聊天","department":"市场部","ID":"11188786"}
	chats["000100"] = chatsobj
	contacts["000100"] = contactsobj
	
	ordered_chats[ordered_chats.len] = "000100"
	getContacts()
	getChats()
	
	channel("000100") */
}

function show_myModal_chat() {
    console.log('in show_myModal_chat');
	$('#myModal_chat').modal('show');
}

function onAddFriend() {
    console.log('in onAddFriend');
	$('#myModal').modal('show');
}

function onCloseAddFriendResult() {
    console.log('in onCloseAddFriendResult');
	// $('#addFriendP').toggleClass('elehide');
    $('#addFriendP').addClass('elehide');
    $('#addFriendN').addClass('elehide');
	$('#myModal_result').modal('hide');
}

$('#myModal_result').on('show.bs.modal', function() {
	$('#myModal_result button[uid^="searchedUser"]').click(function() {
		var _this = $(this);
		var uid = _this.attr("uid");
		// $.ajax();
	});
});

function onSearchUser() {
    console.log('in onSearchUser');
	var txt = $('#newFriendName').val();
	$('#myModal').modal('hide');
	$('#newFriendName').val('');

	$.ajax({
		url: ip + 'searchFriendByName',
		type: 'get',
		datatype: 'json',
		contentType: 'json',
		data: {
			'uid': userId,
			'searchName': txt
		},

		success: function(data) {
			data = JSON.parse(data);

            var _reDiv = $('#myModal_result .chooser');
            _reDiv.empty();

            var size = data.length;
            for(var i=0; i<data.length; ++i) {
                var uid = 'u' + data[i]['id'];
                if(Object.keys(contacts).indexOf(uid) != -1) {
                    size -= 1;
                }
			}

            if(!size) {
                $('#addFriendN').toggleClass('elehide');
			} else {
                $('#addFriendP').toggleClass('elehide');

                for(var i=0; i<data.length; ++i) {
                	var uid = 'u' + data[i]['id'];
                	if(Object.keys(contacts).indexOf(uid) != -1) {
                		continue;
					}

                    //{"id":"10","name":"申通","avatar":"haha","department":"安卓开发工程师:申通","phone":"1017633907915","email":"申通@qq.com"}
                    _reDiv.append("<div class='contact_item'>" +
                        "<div class='avatar'>" +
                        "<img src='" + data[i]['avatar'] + "' class='img'>" +
                        "</div>" +
                        "<div class='info leftfloat' >" +
                        "<h3 class='nickname margin15px'>" +
                        "<span class='nickname_text'>" + data[i]['name'] + "</span>" +
                        "</h3>" +
                        "</div>" +
                        "<div class='addUserBtn'>" +
                        "<button type='button' class='btn btn-primary rightfloat' uid='" + data[i]['id'] + "'>添加</button>" +
                        "</div>" +
                        "</div>");
                }

                $('#addFriendP button').click(function() {
                    var _this = $(this);
                    var uid = _this.attr('uid');

					$.ajax({
						url: ip + "addFri",
						type: 'get',
						contentType: 'application/json; charset=utf-8',
						dataType: 'json',
						data: {
							"fid1": userId,
							"fid2": uid,
							"message": "加个好友呗！"
						},

						success: function(data) {

						},

						error: function() {

						}
					});
                });
			}

            $('#myModal_result').modal('show');
		},
		
		error: function () {
			
        }
	});

}

//发起聊天模态框弹出时
$("#myModal_chat").on("show.bs.modal", function() {
	general_contacts_subfield();
	//发起聊天中选中个人后选框变绿
	$("#people_div .opt i").click(function changeColor() {	
		var o = $(this);
		// var x = document.getElementById(id);
		var classname = o.attr('class');
		if (classname == "web_chat_choose_green") {
			o.attr("class", "web_chat_choose_wireframe");
		} else {
			o.attr("class", "web_chat_choose_green");
		}
	});
	
	$('#group_div .group_item').on('focus', function() {
		var cls = $(this).attr('class');
	})
});


//将联系人分栏显示
function general_contacts_subfield() {
    console.log('in general_contacts_subfield');
	var people = [];
	var group = [];
	for(var k in contacts) {
		var v = contacts[k];
		if(v["dialogType"] == "single") {
			people.push(v);
		} else {
			group.push(v);
		} 
	}
	
	people.sort(cmp);
	function cmp(a, b) {
		return makePy(b['nickname'].charAt(0))[0].toUpperCase() < makePy(a['nickname'].charAt(0))[0].toUpperCase() ? 1 : -1;
	}
	
	var m = new Map();	
	for(var i in people) {
		var init = makePy(people[i]['nickname'].charAt(0))[0].toUpperCase();
		if(m.hasOwnProperty(init)) {
			m[init].push(people[i]);
		} else {
			m[init] = [];
			m[init].push(people[i]);
		}
	}
	
	var prefix = "gen_chat_";
	var _con = $('#people_div .choose_all_List');
	
	_con.empty();
	
	for(var k in m) {
		_con.append("<div><h4 class='contact_title'>" + k + "</h4></div>");
		for(var i in m[k]) {
			var p = m[k][i];
			_con.append("<div class='contact_item'>" + 
							"<div class='opt'>" + 
								"<i class='web_chat_choose_wireframe' id='" +  p['ID'] + "'></i>" +
							"</div>" +
							"<div class='avatar'>" + 
								"<img class='img' alt='' src='" + p['photo'] + "'>" +
							"</div>" +
							"<div class='info'>" + 
								"<h4 class='nickname'>" + p['nickname'] + "</h4>" +
							"</div>" +														
						"</div>");
		}
	}
										
	var _gcon = $('#group_div .choose_all_List');
	_gcon.empty();
	for(var i in group) {
		var g = group[i];
		_gcon.append("<div class='group_item' tabindex='-1'>" +
						"<div class='avatar'>" +
							"<img class='img' alt='' src='" + g['photo'] + "'>" +
						"</div>" +
						"<div class='info'>" + 
							"<h4 class='nickname'>" + g['nickname'] + "</h4>" + 
						"</div>" +
					"</div>")
	}
}


//重置发起聊天页面中的样式
// function default_choose() {
//     var opt = document.getElementsByName("i_color");
//     opt.setAttribute("class","web_chat_choose_wireframe");
//
//     var change_select_people = document.getElementById("change_select_people");
//     var change_select_groups = document.getElementById("change_select_groups");
//
//     var people_div = document.getElementById("people_div");
//     var group_div = document.getElementById("group_div");
//
//     var change_select_people_className =  change_select_people.className;
//     var change_select_groups_className =  change_select_groups.className;
//
//     if(change_select_groups_className=="nav_tab selected"&&change_select_people_className=="nav_tab"){
//         change_select_groups.setAttribute("class","nav_tab");
//         change_select_people.setAttribute("class","nav_tab selected");
//         people_div.setAttribute("style","display: block");
//         group_div.setAttribute("style","display: none");
//     }
//
// }

// 点击文本框样式不改变，边框颜色不变
function click_input(){
    console.log('in click_input');
    var input = document.getElementsByClassName("input_update");
    input.setAttribute("style","border:none #FFFFFF border-bottom:#777777 solid 1px;")
}
// 保存个人信息的修改
$("#saveUpdate_btn").click(function(){
    // alert("Value: " + $("#test").val());
    contacts[userId].nickname = $("#myinfo_nickName").val();
    $("#my_nickName").text(contacts[userId].nickname);
    $("#my_nickName_Top").text(contacts[userId].nickname);
    $("#myinfo_nickName").attr("value",contacts[userId].nickname);
   // alert(contacts[userId].nickname);
    //alert($("#myinfo_nickName").val());
});

//点击头像，显示个人信息
$("#headPic_div").on('click',function () {
    $("#right_default").attr("style","display: none");
    $("#right_contacts").attr("style","display: none");
    $("#right_myself").show();
});


function showUserInfo() {
    console.log('in showUserInfo');
    uid = 'u' + userId;
    $("#headPic").attr("src",contacts[uid].photo);

    $("#my_nickName_Top").text(contacts[uid].nickname);

    $("#my_photo").attr("src",contacts[uid].photo);
    $("#myinfo_userID").text(uid);
    $("#my_nickName").text(contacts[uid].nickname);
    $("#myinfo_userName").text(contacts[uid].userName);
    $("#myinfo_department").text(contacts[uid].department);
    $("#myinfo_nickName").attr("value",contacts[uid].nickname);
}

//个人信息
$(document).ready(function(){
    // uid = 'u' + userId;
    // $("#headPic").attr("src",contacts[uid].photo);
    //
    // $("#my_nickName_Top").text(contacts[uid].nickname);
    //
    // $("#my_photo").attr("src",contacts[uid].photo);
    // $("#myinfo_userID").text(uid);
    // $("#my_nickName").text(contacts[uid].nickname);
    // $("#myinfo_userName").text(contacts[uid].userName);
    // $("#myinfo_department").text(contacts[uid].department);
    // $("#myinfo_nickName").attr("value",contacts[uid].nickname);
});

//更换头像
$("#change_my_icon_btn1").click(function () {
    var change_my_icon_btn = document.getElementById("change_my_icon_btn1");
    var camera = document.getElementById("camera");

    change_my_icon_btn.addEventListener('click', function (e) {
        var evt = new MouseEvent("click", {bubbles: false, cancelable: true, view: window});
        camera.dispatchEvent(evt);
    }, false);
})

$("#camera").change(function(e) {
    for (var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function(e) {
            var src = e.target.result;
            $("#my_photo").attr("src",src);
            $("#headPic").attr("src",src);
        }
    }
});

$("#btnShowMember").click(function() {
    var _obj = $(this);
    var flag = _obj.attr("flag");
    if(flag == "show") {
        $(".group_member_panel").slideUp("quick");
        $(this).attr("flag", "hide");
        $(this).attr("class", "directDown");
        return;
    }

    var iid = _obj.attr("gid");
    var dialogType = contacts[iid].dialogType;

    var _panel = $("div.group_member_panel");
    _panel.empty();

    if(dialogType=="multi") {
        var gid = contacts[iid].ID;
        $.ajax({
            url: ip + "getGroupMembers",
            type: "get",
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            data: {
                'uid': userId,
                'gid': gid
            },

            success: function(data){
                console.log(data);
                var mid = contacts[iid].manager;
                data = JSON.parse(data);
                if(mid==userId) {
                    for(var i=0; i<data.length; ++i) {
                        _panel.append("<div class='memberItem'>" +
                            "<img src='"+ data[i]['avatar'] +"'>" +
                            "<button class='delMember' uid='" + data[i]['userid'] + "'></button>" +
                            "<span>"+ data[i]['username'] +"</span>" +
                            "</div>")
                    }

                    $(".delMember").click(function() {
                        var uid = $(this).attr("uid");
                        var _delBtn = $(this);

                        $.ajax({
                            url: ip + "delMemberFromGroup",
                            type: "get",
                            datatype: "json",
                            contentType: "application/json; charset=utf-8",
                            data: {
                                'uid': userId,
                                'gid': gid,
                                'mid': uid
                            },

                            success: function(data) {
                                if(data['success']=='yes') {
                                    _delBtn.parent().remove();
                                }
                            },

                            error: function() {

                            }
                        });
                    });
                } else {
                    for(var i=0; i<data.length; ++i) {
                        _panel.append("<div class='memberItem'>" +
                            "<img src='"+ data[i]['avatar'] +"'>" +
                            // "<button class='delMember' uid='" + data[i]['userid'] + "'></button>" +
                            "<span>"+ data[i]['username'] +"</span>" +
                            "</div>")
                    }
                }


                _panel.append("<div id='addMember'>");
                $('#addMember').click(function() {
                    var people = [];
                    for(var k in contacts) {
                        var v = contacts[k];
                        if(v["dialogType"] == "single") {
                            people.push(v);
                        }
                    }

                    people.sort(cmp);
                    function cmp(a, b) {
                        return makePy(b['nickname'].charAt(0))[0].toUpperCase() < makePy(a['nickname'].charAt(0))[0].toUpperCase() ? 1 : -1;
                    }

                    var m = new Map();
                    for(var i in people) {
                        var init = makePy(people[i]['nickname'].charAt(0))[0].toUpperCase();
                        if(m.hasOwnProperty(init)) {
                            m[init].push(people[i]);
                        } else {
                            m[init] = [];
                            m[init].push(people[i]);
                        }
                    }

                    var _con = $('#chooseMember .choose_all_List');
                    _con.empty();

                    for(var k in m) {
                        _con.append("<div><h4 class='contact_title'>" + k + "</h4></div>");
                        for(var i in m[k]) {
                            var p = m[k][i];
                            _con.append("<div class='contact_item'>" +
                                "<div class='opt'>" +
                                "<i class='web_chat_choose_wireframe' id='" +  p['ID'] + "'></i>" +
                                "</div>" +
                                "<div class='avatar'>" +
                                "<img class='img' alt='' src='" + p['photo'] + "'>" +
                                "</div>" +
                                "<div class='info'>" +
                                "<h4 class='nickname'>" + p['nickname'] + "</h4>" +
                                "</div>" +
                                "</div>");
                        }
                    }

                    $('#chooseMember').modal('show');
                });

                $(".group_member_panel").slideDown("quick");
                _obj.attr("class", "directUp");
                _obj.attr("flag", "show");
            },

            error: function() {

            }
        });
    } else {

    }

});

$("#chooseMember").on("show.bs.modal", function() {
    $("#chooseMember .opt i").click(function changeColor() {
        var o = $(this);
        var classname = o.attr('class');
        if (classname == "web_chat_choose_green") {
            o.attr("class", "web_chat_choose_wireframe");
        } else {
            o.attr("class", "web_chat_choose_green");
        }
    });
});

function onInviteMember() {
    var _cis = $("i[class*='web_chat_choose_green']");
    var ids = [];
    _cis.each(function () {
        ids.push($(this).attr('id'));
    });

    var gid = $('#btnShowMember').attr("gid");
    var mid = contacts[gid]['manager'];
    gid = contacts[gid].ID;

    for(var i=0; i<ids.length; ++i) {
        var id = ids[i];
        $.ajax({
            url: ip + 'addMemberToGroup',
            type: 'get',
            datatype: 'json',
            contentType: 'application/json; charset=utf-8',
            data: {
                "mid": id,
                "uid": userId,
                "gid": gid
            },

            success: function(data) {
                if(data['success']=='yes') {
                    var p = contacts['u'+id];
                    $("#addMember").before("<div class='memberItem'>" +
                        "<img src='"+ p['photo'] +"'>" +
                        "<button class='delMember' uid='" + p['ID'] + "'></button>" +
                        "<span>"+ p['username'] +"</span>" +
                        "</div>");
                }
            },

            error: function() {

            }
        });
    }


    $('#chooseMember').modal('hide');
}